package com.example.demo.service;

/**
 * @version 1.0
 * @author： wbxz
 * @date： 2021-08-10 15:22
 */

import cn.hutool.core.util.ReUtil;
import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeQueryModel;
import com.alipay.api.domain.AlipayTradeRefundModel;
import com.alipay.api.request.AlipayTradeFastpayRefundQueryRequest;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradeFastpayRefundQueryResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.example.demo.entity.AlipayBean;
import com.example.demo.entity.AlipayProperties;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;


@Component
public class Alipay {

    /**
     * 支付接口
     * @param alipayBean
     * @return
     * @throws AlipayApiException
     */
    @Autowired
    AlipayProperties alipayProperties;
    public String pay(AlipayBean alipayBean) throws AlipayApiException {
        // 1、获得初始化的AlipayClient
        String serverUrl = alipayProperties.getGatewayUrl();
        String appId = alipayProperties.getApp_id();
        String privateKey = alipayProperties.getPrivateKey();
        String format = "json";
        String charset = alipayProperties.getCharset();
        String alipayPublicKey = alipayProperties.getPublicKey();
        String signType = alipayProperties.getSign_type();
        String returnUrl = alipayProperties.getReturn_url();
        String notifyUrl = alipayProperties.getNotify_url();
        AlipayClient alipayClient = new DefaultAlipayClient(serverUrl, appId, privateKey, format, charset, alipayPublicKey, signType);
        // 2、设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        // 页面跳转同步通知页面路径
        alipayRequest.setReturnUrl(returnUrl);
        // 服务器异步通知页面路径
        alipayRequest.setNotifyUrl(notifyUrl);
        //账户订单号
        String out_trade_no = new Date().getTime()+ UUID.randomUUID().toString();
        alipayBean.setOut_trade_no(out_trade_no);
        System.out.println("订单号:"+out_trade_no);
        // 封装参数
        alipayRequest.setBizContent(JSON.toJSONString(alipayBean));
        // 3、请求支付宝进行付款，并获取支付结果   交易
        String result = alipayClient.pageExecute(alipayRequest).getBody();
        // 返回付款信息
        System.out.println("result："+result);


        //查询
        queryInfo(alipayClient, out_trade_no,40000);


        //退款
        new Timer().schedule(new TimerTask() {
            @SneakyThrows
            @Override
            public void run() {
                AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
                AlipayTradeRefundModel alipayTradeRefundModel = new AlipayTradeRefundModel();
                alipayTradeRefundModel.setOutTradeNo(out_trade_no);
                alipayTradeRefundModel.setRefundAmount("30");
                alipayTradeRefundModel.setOutRequestNo("1111111");
                alipayTradeRefundModel.setRefundReason("用的不爽，不能超神");
                request.setBizModel(alipayTradeRefundModel);
                AlipayTradeRefundResponse execute = alipayClient.execute(request);
                if(execute.isSuccess()){
                    System.out.println("支付宝交易号       : " + execute.getTradeNo());
                    System.out.println("商家订单号         : " + execute.getOutTradeNo());
                    System.out.println("金额是否发生变化         : " + execute.getFundChange());
                    System.out.println("退款金额         : " + execute.getRefundFee());
                }
            }
        },50000);

        //查询退款是否成功
        new Timer().schedule(new TimerTask() {
            @SneakyThrows
            @Override
            public void run() {
                AlipayTradeFastpayRefundQueryRequest request = new AlipayTradeFastpayRefundQueryRequest();
                AlipayTradeRefundModel alipayTradeRefundModel = new AlipayTradeRefundModel();
                alipayTradeRefundModel.setOutTradeNo(out_trade_no);
                alipayTradeRefundModel.setRefundAmount("30");
                alipayTradeRefundModel.setOutRequestNo("1111111");
                request.setBizModel(alipayTradeRefundModel);
                AlipayTradeFastpayRefundQueryResponse response = alipayClient.execute(request);
               if(response.isSuccess()){
                   System.out.println("支付宝交易号       : " + response.getTradeNo());
                   System.out.println("商家订单号         : " + response.getOutTradeNo());
                   System.out.println("退款状态         : " + response.getRefundStatus());
                   System.out.println("退款原因         : " + response.getRefundReason());
                   System.out.println("退分账明细信息         : " + response.getRefundRoyaltys());
               }
            }
        },70000);


        //查询
        queryInfo(alipayClient, out_trade_no, 80000);




        return result;
    }

    private void queryInfo(AlipayClient alipayClient, String out_trade_no, int i) {
        new Timer().schedule(new TimerTask() {
            @SneakyThrows
            @Override
            public void run() {
                //设置请求参数
                AlipayTradeQueryRequest queryRequest = new AlipayTradeQueryRequest();

                AlipayTradeQueryModel queryModel = new AlipayTradeQueryModel();
                // 设置订单编号来查询
                queryModel.setOutTradeNo(out_trade_no);
                queryRequest.setBizModel(queryModel);
                AlipayTradeQueryResponse queryResponse = alipayClient.execute(queryRequest);
                if (queryResponse.isSuccess()) {
                    // 请求成功
                    System.out.println("支付宝交易号       : " + queryResponse.getTradeNo());
                    System.out.println("商家订单号         : " + queryResponse.getOutTradeNo());
                    System.out.println("买家支付宝账号     : " + queryResponse.getBuyerLogonId());
                    System.out.print("交易状态:");
                    switch (queryResponse.getTradeStatus()) {
                        case "WAIT_BUYER_PAY":
                            System.out.println("交易创建，等待买家付款");
                            break;
                        case "TRADE_CLOSED":
                            System.out.println("未付款交易超时关闭，或支付完成后全额退款");
                            break;
                        case "TRADE_FINISHED":
                            System.out.println("交易结束，不可退款");
                            break;
                        case "TRADE_SUCCESS":
                            System.out.println("交易支付成功");
                            break;
                    }

                    System.out.println("交易的订单金额     : " + queryResponse.getTotalAmount());
                } else {
                    System.err.println("延时主动向支付宝查询失败！");
                }
            }
        },i);
    }

    public static void main(String[] args) {
        String a = "6";
        boolean match = ReUtil.isMatch("^[16]$", a);
        System.out.println("match = " + match);
        
    }
}

